<template>
	<view class="serveView">
		<nav-bar isBack title="在线咨询"></nav-bar>
		<view class="msgListCont" @touchstart="opbar.action=''">
			<scroll-view scroll-y="true" class="messagesView" :scroll-top="messagesScrollTop" :scroll-into-view="scrollIntoView" @scroll="scrollEvent" @scrolltoupper="scrolltoupper">
				<view class="tips" v-if="hisData.page===hisData.total">没有更多了</view>
				<view class="tips" :style="{'opacity':hisData.loading?1:0}">加载中...</view>
				<template v-for="(item,index) in messages">
					<view :id="'ele_'+item.ele_id" :key="index">
						<msg-item :msgData="item" :userID="timData.userID" @msgItemTap="msgItemTap"></msg-item>
					</view>
				</template>
			</scroll-view>
		</view>
		
		<view class="opbar">
			<view class="cell1">
				<input type="text" v-model="opbar.input" placeholder="回复点什么" confirm-type="send" @confirm="opbarInputConfirm"/>
				<text class="iconfont iconhuaban52" @tap="opbarBtnTap('emoji')" :class="opbar.action=='emoji' && 'active'"></text>
				<text class="iconfont iconhuaban65"  @tap="opbarBtnTap('menu')" :class="opbar.action=='menu' && 'active'"></text>
			</view>
			<view class="cell2" v-if="opbar.action=='menu'">
				<swiper :duration="500" :current="opbar.menu.current"
					@change="(e)=>{opbar.menu.current = e.detail.current}">
					<swiper-item class="menu-box" v-for="(item1,index1) in menuList" :key="index1">
						<view class="menu-item" v-for="item2 in item1" @tap="menuItemTap(item2.name)">
							<text class="iconfont" :class="item2.icon"></text>
							<text>{{item2.name}}</text>
						</view>
					</swiper-item>
				</swiper>
				<view class="dots">
					<view class="dot" :class="{'active':index == opbar.menu.current}" v-for="(item,index) in menuList"
						:key="index"></view>
				</view>
			</view>
			<view class="cell3" v-if="opbar.action=='emoji'">
				<scroll-view scroll-y="true">
					<text class="emojiItem" v-for="(item,index) in opbar.emoji.list" @tap="opbar.input+=item"
						:key='index'>{{item}}</text>
				</scroll-view>
			</view>
		</view>
		
		<u-popup v-model="goodsShow" mode="bottom" height="100%">
			<goods-popup v-if="goodsShow" @sendPopupMsg="sendPopupMsg" @close="()=>{goodsShow=false}"></goods-popup>
		</u-popup>
		<u-popup v-model="caseShow" mode="bottom" height="100%">
			<case-popup v-if="caseShow" @sendPopupMsg="sendPopupMsg" @close="()=>{caseShow=false}"></case-popup>
		</u-popup>
		<u-popup v-model="storeShow" mode="bottom" height="100%">
			<store-popup v-if="storeShow" @sendPopupMsg="sendPopupMsg" @close="()=>{storeShow=false}"></store-popup>
		</u-popup>
		<u-popup v-model="designShow" mode="bottom" height="100%">
			<designer-popup v-if="designShow" @sendPopupMsg="sendPopupMsg" @close="()=>{designShow=false}"></designer-popup>
		</u-popup>
		<u-popup v-model="teamShow" mode="bottom" height="100%">
			<team-popup v-if="teamShow" @sendPopupMsg="sendPopupMsg" @close="()=>{teamShow=false}"></team-popup>
		</u-popup>
		<u-popup v-model="quickShow" mode="bottom" height="100%">
			<quick-popup v-if="quickShow" @sendPopupMsg="sendPopupMsg" @close="()=>{quickShow=false}"></quick-popup>
		</u-popup>
		<u-popup v-model="csShow" mode="bottom" height="100%">
			<cs-popup :chat_id="chat_id" v-if="csShow" @sendPopupMsg="sendPopupMsg" @close="()=>{csShow=false}"></cs-popup>
		</u-popup>
		<u-popup v-model="userInfoShow" mode="bottom" height="100%">
			<user-info-popup :chat_id="chat_id" v-if="userInfoShow" @sendPopupMsg="sendPopupMsg" @close="()=>{userInfoShow=false}"></user-info-popup>
		</u-popup>
	</view>
</template>

<script>
	import navBar from "@/components/navBar/navBar"
	import msgItem from "../components/msg-item.vue"
	import goodsPopup from "../components/goods-popup.vue"
	import storePopup from "../components/store-popup.vue"
	import casePopup from "../components/case-popup.vue"
	import designerPopup from "../components/designer-popup.vue"
	import teamPopup from "../components/team-popup.vue"
	import quickPopup from "../components/quick-popup.vue"
	import csPopup from "../components/cs-popup.vue"
	import userInfoPopup from "../components/userInfo-popup.vue"
	// import TIMSDK from '../js_sdk/tim-sdk/index.js'
	// import TIMUploadPlugin from '../js_sdk/tim-upload-plugin/index.js'
	import customeApi from '@/service/custome.js'
	// let tim = TIMSDK.create({
	// 	SDKAppID: 1400501255
	// });
	// tim.registerPlugin({
	// 	'tim-upload-plugin':TIMUploadPlugin
	// })
	// tim.setLogLevel(1);
	export default {
		components: {
			navBar,
			msgItem,
			casePopup,
			goodsPopup,
			storePopup,
			designerPopup,
			teamPopup,
			quickPopup,
			csPopup,
			userInfoPopup
		},
		data() {
			return {
				messages:[],
				messagesScrollTop:0,
				userInfoShow:false,
				teamShow:false,
				goodsShow:false,
				caseShow:false,
				storeShow:false,
				designShow:false,
				designerShow:false,
				quickShow:false,
				csShow:false,
				opbar: {
					action: '',
					input: '',
					menu: {
						current: 0,
						list: [
							{"name": "拍照",'icon': "iconhuaban113"},
							{"name": "图片",'icon': "iconhuaban24"},
							{"name": "快捷语言",'icon': "iconhuaban34"},
							{"name": "用户信息",'icon': "iconhuaban43"},
							{"name": "推荐商品",'icon': "iconhuaban43"},
							{"name": "推荐案例",'icon': "iconhuaban63"},
							{"name": "推荐商家",'icon': "iconhuaban72"},
							{"name": "推荐设计师",'icon': "iconhuaban82"},
							{"name": "推荐施工队",'icon': "iconhuaban92"},
							{"name": "转客服",'icon': "iconhuaban53"},
						]
					},
					emoji: {
						list: ['😠', '😩', '😲', '😞', '😵', '😰', '😒', '😍', '😤', '😜', '😝', '😋', '😘', '😚', '😷',
							'😳', '😃', '😅', '😆', '😁', '😂', '😊', '😄', '😢', '😭', '😨', '😣', '😡', '😌', '😖',
							'😔', '😱', '😪', '😏', '😓', '😥', '😫', '😉'
						]
					}
				},
				timData: {
					status: false,
					userID: '',
					userSig: '',
					to: ''
				},
				hisData:{
					page: 0,
					pagesize: 10,
					begintime: "",
					endtime: "",
					total:null,
					loading:false,
					ele_id:''
				},
				scrollIntoView:'',
				partner_type:'shop',
				partner_id:18,
				chat_id:''
			}
		},
		computed: {
			navHeight() {
				return this.$store.state.system.navBarHeight
			}, // Nav栏高度
			statusBarHeight(){
				let systemInfo =  uni.getSystemInfoSync()
				return systemInfo.statusBarHeight || 0
			},
			menuList() {
				let ary = [];
				this.opbar.menu.list.map((item, index) => {
					let targetIndex = parseInt(index / 8);
					if (!ary[targetIndex]) {
						ary[targetIndex] = []
					}
					ary[targetIndex].push(item)
				})
				return ary
			},
			timMsg(){
				return this.$store.state.tim.msg
			},
		},
		onLoad(options) {
			if(uni.getStorageSync('timInfo')){
				this.timData.userID=uni.getStorageSync('timInfo').userID
				this.timData.userSig=uni.getStorageSync('timInfo').userSig
			}
			if(options.partner_type){
				this.partner_type=options.partner_type
			}
			if(options.chat_id){
				this.chat_id=options.chat_id;
			}else{
				uni.navigateBack();
				return
			}
			if(options.to){
				this.timData.to=options.to;
				this.getChatHis();
				// this.timLoginEvent()
			}else{
				uni.navigateBack();
			}
			// if(uni.getStorageSync('timDataInfo')){
			// 	this.timData=uni.getStorageSync('timDataInfo');
			// }else{
				
			// }
		},
		onShow() {
			if(!this.$store.state.tim.status){
				if(this.$store.state.index.token){
					let tk = this.$store.state.index.token;
					this.$store.commit('index/token','');
					this.$store.commit('index/token',tk);
				}
			}
		},
		methods: {
			getWelcomeData(){
				customeApi.welcome({
					partner_type:this.partner_type,
					partner_id:this.partner_id,
				}).then(res=>{
					if(res.code==1){
						this.chat_id=res.data.chat_id;
						let p={
							payload:{
								data: JSON.parse(res.data.msg_content).Data,
								description: JSON.parse(res.data.msg_content).Desc,
								extension: '猜你想问'
							},
							ID:'',
							from:'welcome'
						}
						this.messages.push(p)
					}
				})
			},
			getQuestionbyidUser(chat_id,content){
				customeApi.questionbyidUser({
					chat_id,
					content
				}).then(res=>{
					if(res.code==1){
						let p={
							payload:{
								data: JSON.parse(res.data.msg_content).Data,
								description: JSON.parse(res.data.msg_content).Desc,
								extension: '以下选项请选择'
							},
							ID:'',
							from:'questionbyid'
						}
						this.messages.push(p)
					}
				})
			},
			getQuestionbyidData(chat_id,knowledge_id){
				customeApi.questionbyid({
					chat_id,
					knowledge_id
				}).then(res=>{
					if(res.code==1){
						let p={
							payload:{
								data: JSON.parse(res.data.msg_content).Data,
								description: JSON.parse(res.data.msg_content).Desc,
								extension: '以下选项请选择'
							},
							ID:'',
							from:'questionbyid'
						}
						this.messages.push(p)
						// console.log(JSON.parse(JSON.parse(res.data.msg_content).Data).is_human)
						if(JSON.parse(JSON.parse(res.data.msg_content).Data).is_human=='1'){
							this.getConnect(chat_id);
							
						}
					}
				})
			},
			//获取客服信息
			getConnect(chat_id){
				customeApi.connect({
					chat_id
				}).then(res=>{
					if(res.code==1 && res.data.status==1){
						this.timData.userID=res.data.im_user;
						this.timData.to=res.data.kefu_account;
						this.timData.userSig=res.data.sig;
						uni.setStorageSync('timDataInfo',{
							...this.timData,
							status:false
						})
						this.timLoginEvent()
					}else{
						this.$utils.showErr({title: res.data.msg})
					}
				})
			},
			//登录TIM
			timLoginEvent() {
				let promise = tim.login({
					userID: this.timData.userID,
					userSig: this.timData.userSig
				});
				promise.then((imResponse) => {
					this.timData.status = true;
					if (imResponse.data.repeatLogin === true) {
						// 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
						console.log(imResponse.data.errorInfo);
					}
					tim.on(this.$tim.sdk.EVENT.MESSAGE_RECEIVED, this.timMessageReceived);
					this.getChatHis();
				}).catch((imError)=> {
					this.timData.status = false;
					console.warn('login error:', imError); // 登录失败的相关信息
				});
			},
			timMessageReceived(event) {
				console.log(event)
				if (event.name == "onMessageReceived") {
					event.data.map(item=>{
						if(item.from == "administrator" || item.from==this.timData.to){
							this.messages.push(item)
						}
					})
				}
			},
			//发送图片消息
			async timSendImg(imgdata){
				let teampIndex = await this.createTempImg(imgdata);
				let message = this.$tim.tim.createImageMessage({
				    to: this.timData.to,
				    conversationType: this.$tim.sdk.TYPES.CONV_C2C,
				    payload: { file: imgdata },
				    onProgress: function(event) { console.log('file uploading:', event) }
				});
				// 3. 发送图片
				let promise = this.$tim.tim.sendMessage(message);
				promise.then((imResponse)=> {
					this.$set(this.messages,teampIndex,imResponse.data.message);
				}).catch((imError)=> {
					let item= this.messages[teampIndex];
					item.sendFail=true;
					item.sending=false;
					this.$set(this.messages,teampIndex,item);
				});
			},
			//发送自定义消息
			timSendMsg(data,description,extension) {
				if(typeof data == "object"){
					data=JSON.stringify(data)
				}
				if(typeof description == "object"){
					description=JSON.stringify(description)
				}
				if(typeof extension == "object"){
					extension=JSON.stringify(extension)
				}
				let message = this.$tim.tim.createCustomMessage({
					to: this.timData.to,
					conversationType: this.$tim.sdk.TYPES.CONV_C2C,
					payload: {
						data:data || '',
						description: description || '',
						extension: extension || ''
					}
				});
				this.createTempMsg(data,description,extension);
				let promise2 = this.$tim.tim.sendMessage(message);
				promise2.then((imResponse) => {
					for(let i = this.messages.length -1 ; i>=0;i--){
						let item = this.messages[i];
						if(item && item.sending && item.payload.extension == imResponse.data.message.payload.extension){
							this.$set(this.messages,i,imResponse.data.message);
							break;
						}
					}
				}).catch((imError) => {
					for(let i = this.messages.length -1 ; i>=0;i--){
						let item = this.messages[i];
						if(item && item.sending && item.payload.extension == extension){
							item.sendFail=true;
							item.sending=false;
							this.$set(this.messages,i,item);
							break;
						}
					}
				});
			},
			//加载中占位消息
			createTempMsg(data,description,extension){
				let p={
					payload:{
						data,
						description,
						extension
					},
					ID:'',
					sending:true,
					sendFail:false,
					from:this.timData.userID
				}
				this.messages.push(p);
			},
			//加载中占位图片消息
			async createTempImg(imgdata){
				let url =imgdata.tempFilePaths[0];
				let width=0,height=0;
				let info = ( await uni.getImageInfo({src: imgdata.tempFilePaths[0]}) )[1];
				width = info.width;
				height = info.height;
				let p={
					payload:{
						imageFormat:3,
						imageInfoArray:[
							{
								url,
								width,
								height
							},
							{
								url,
								width,
								height
							}
						],
						uuid:'',
						extension:this.getUuid()
					},
					ID:'',
					sending:true,
					sendFail:false,
					from:this.timData.userID,
					type:'TIMImageElem',
				}
				this.messages.push(p);
				return this.messages.length-1
			},
			//重发自定义消息
			resendMsg(parms){
				for(let i = this.messages.length -1 ; i>=0;i--){
					let item = this.messages[i];
					if(item && item.sendFail && item.payload.extension == parms.payload.extension){
						this.messages.splice(i,1);
						this.timSendMsg(parms.payload.data,parms.payload.description,parms.payload.extension);
						break;
					}
				}
			},
			// 重发图片
			resendImg(parms){
				for(let i = this.messages.length -1 ; i>=0;i--){
					let item = this.messages[i];
					if(item && item.sendFail && item.type=='TIMImageElem' && item.payload.extension == parms.payload.extension){
						this.messages.splice(i,1);
						this.timSendImg({
							tempFilePaths:[parms.payload.imageInfoArray[0].url]
						})
						break;
					}
				}
			},
			// 内容确认事件
			opbarInputConfirm(event){
				if(!this.$store.state.tim.status){
					uni.showToast({
						title: '正在连接',
						duration: 2000,
						icon:'none'
					});
					
					uni.getStorage({
					    key: 'timInfo',
					    success: (res) => {
							console.log(res,'kefukfkfkf')
					        this.$tim.login(res.userID, res.userSig)
					    }
					});
					return
				}
				let value = event.target.value;
				let chat_id = this.chat_id;
				this.timSendMsg(value,{chat_id,format:'string'},this.getUuid())
				this.opbar.input=''
			},
			// 键盘菜单点击事件
			menuItemTap(type){
				if(type=="图片"){
					uni.chooseImage({
					    count: 1, //默认9
					    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					    sourceType: ['album'], //从相册选择
					    success:(res)=> {
							this.timSendImg(res)
					    }
					});
					return
				}
				if(type=="拍照"){
					uni.chooseImage({
					    count: 1, //默认9
					    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					    sourceType: ['camera'], //从相册选择
					    success:(res)=> {
							this.timSendImg(res)
					    }
					});
					return
				}
				if(type=="用户信息"){
					this.userInfoShow=true
				}
				if(type=="推荐商品"){
					this.goodsShow=true
				}
				if(type=="推荐案例"){
					this.caseShow=true
				}
				if(type=="推荐商家"){
					this.storeShow=true
				}
				if(type=="推荐设计师"){
					this.designShow=true
				}
				if(type=="推荐施工队"){
					this.teamShow=true
				}
				if(type=="快捷语言"){
					this.quickShow=true
				}
				if(type=="转客服"){
					this.csShow=true
				}
			},
			// 消息项点击事件传递
			msgItemTap(type,parms){
				if(type=='LIST_ITEM'){
					this.getQuestionbyidData(parms.chat_id,parms.id);
					return
				}
				if(type=='MSG_FAIL'){
					uni.showModal({
					    title: '提示',
					    content: '是否重发?',
					    success:(res)=> {
					        if (res.confirm) {
								this.resendMsg(parms)
					        } else if (res.cancel) {}
					    }
					});
				}
				
				if(type=='IMG_FAIL'){
					uni.showModal({
					    title: '提示',
					    content: '是否重发?',
					    success:(res)=> {
					        if (res.confirm) {
								this.resendImg(parms)
					        } else if (res.cancel) {}
					    }
					});
				}
				if(type == 'GOODS'){
					console.log(parms)
					uni.navigateTo({
						url:'/pages/mall/goods/goods?id=' + parms.product_id
					})
					return
				}
			},
			// 生成uuid
			getUuid() {
			    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			        var r = Math.random() * 16 | 0,
			            v = c == 'x' ? r : (r & 0x3 | 0x8);
			        return v.toString(16);
			    });
			},
			isScrollBottom(flag){
				let view = uni.createSelectorQuery().in(this).select(".messagesView");
				if (!view) {
					return
				}
				let toBottom = 0;
				view.fields({
					size: true,
					scrollOffset: true
				}, data => {
					toBottom = data.scrollHeight - data.scrollTop - data.height;
					if(toBottom<100 || flag){
						this.$nextTick(()=>{
							this.messagesScrollTop = data.scrollHeight
						})
					}
				}).exec();
			},
			opbarBtnTap(type){
				this.opbar.action=this.opbar.action==type?'':type
			},
			getChatHis(type='init'){
				if(this.hisData.loading) return ;
				this.hisData.loading = true;
				customeApi.chatHis({
					chat_id: this.chat_id, 
					page: this.hisData.page+1,
					pagesize: this.hisData.pagesize,
					begintime: this.hisData.begintime,
					endtime: this.hisData.endtime
				}).then(res=>{
					if(res.code==1){
						if(res.data.list.length<1){
							return
						}
						if(this.messages[0]){
							this.hisData.ele_id = this.messages[0].ele_id;
						}
						this.hisData.page = this.hisData.page + 1;
						this.hisData.total = Math.ceil(res.data.total/this.hisData.pagesize);
						
						res.data.list.map(item=>{
							item.ele_id = this.getUuid();
							this.messages.unshift(item)
						})
						if(type == 'init'){
							this.hisData.endtime = res.data.list[0].time;
							this.$nextTick(()=>{
								this.isScrollBottom(true)
							})
							return
						}
						if(type = "history"){
							this.$nextTick(()=>{
								if(this.hisData.ele_id){
									this.scrollIntoView = "ele_"+this.hisData.ele_id
								}
							})
						}
					}
				}).catch(err=>{
					
				}).finally(r=>{
					setTimeout(()=>{
						this.hisData.loading = false;
					},800)
				})
			},
			scrolltoupper(){
				if(this.hisData.page===this.hisData.total){
					return
				}
				this.getChatHis('history');
			},
			scrollEvent(event){
				if(event.detail.scrollTop>50){
					this.hisData.ele_id = "";
				}
			},
			// 发送快捷消息
			sendQuickMsg(value){
				if(!value){
					return
				}
				let chat_id = this.chat_id;
				this.timSendMsg(value,{chat_id,format:'string'},this.getUuid())
				this.quickPopupShow = false;
			},
			//发送弹窗推荐消息
			sendPopupMsg(datas,msgType='string'){
				let chat_id = this.chat_id;
				this.timSendMsg(datas,{chat_id,format:msgType},this.getUuid());
			}
		},
		
		watch: {
			messages(newVal,oldVal) {
				this.isScrollBottom()
			},
			timMsg(newVal,oldVal){
				if(newVal){
					if(newVal.from == "administrator" || newVal.from==this.timData.to){
						this.messages.push(newVal)
					}
				}
			}
		},
		onUnload() {
			if(this.timData.to){
				this.$store.commit('tim/SET_timNoread', {
					account:this.timData.to,
					value:0
				})
			}
		}
	}
</script>

<style lang="scss">
	@import "../components/cl-uni/index.scss";
	@import "../components/cl-uni/theme.scss";
	page {
		width: 100%;
		height: 100%;
	}

	.serveView {
		.cl-filter-item__dropdown-box,{
			border-radius:0 0 18rpx 18rpx;
		}
		.cl-filter-bar{
			height: 104rpx;
		}
		.cl-filter-item,.cl-filter-bar{
			border-radius: 18rpx 18rpx 0 0;
			&.active{
			color: #A98F68;
			}
		}
		cl-filter-bar{
			border-radius: 18rpx 18rpx 0 0;
		}
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		background: #F8F8F8;

		.msgListCont {
			flex: 1;
			min-height: 0;
			overflow-y: hidden;

			scroll-view {
				width: 100%;
				height: 100%;
			}
			.tips{
				font-size: 28rpx;
				padding: 5rpx 0;
				text-align: center;
				color: #666;
			}
		}

		.opbar {
			background: #fff;

			.cell1 {
				width: 100%;
				height: 112rpx;
				display: flex;
				align-items: center;

				input {
					background: #F8F8F8;
					border-radius: 50rpx;
					padding-left: 20rpx;
					flex: 1;
					height: 64rpx;
					margin: 0 20rpx;
				}

				.iconfont {
					font-size: 50rpx;
					margin-right: 20rpx;
					text-align: center;
					color: #6C6C6C;

					&.active {
						color: #C3AB7C;
					}
				}
			}

			.cell2 {
				width: 100%;
				height: 452rpx;
				background: #FFFFFF;
				position: relative;

				.menu-box {
					display: flex;
					flex-wrap: wrap;

					.menu-item {
						width: 25%;
						display: flex;
						align-items: center;
						flex-direction: column;
						font-size: 20rpx;
						color: #939393;

						.iconfont {
							width: 104rpx;
							background-color: #F8F8F8;
							height: 104rpx;
							line-height: 104rpx;
							text-align: center;
							font-size: 56rpx;
							color: #6C6C6C;
							margin-bottom: 12rpx;
							border-radius: 16rpx;
						}
					}
				}

				.dots {
					position: absolute;
					bottom: 20rpx;
					width: 100%;
					display: flex;
					justify-content: center;
					z-index: 99;
					align-items: center;

					.dot {
						width: 12rpx;
						height: 12rpx;
						background: #6C6C6C;
						border-radius: 50%;
						opacity: 0.2;
						margin: 0 5rpx;

						&.active {
							opacity: 1;
						}
					}
				}
			}

			.cell3 {
				height: 452rpx;

				scroll-view {
					height: 100%;

					.emojiItem {
						display: block;
						float: left;
						text-align: center;
						width: calc(100% / 6);
						font-size: 60rpx;
						margin: 14rpx 0;
					}
				}
			}
		}
		
	}
</style>
